package com.k.ums.service;

import com.k.ums.dao.SysMenuMapper;
import com.k.ums.model.MenuTree;
import com.k.ums.model.SysMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2022/1/14
 */
@Service
public class SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    public List<SysMenu> selectMenuList(SysMenu sysMenu) {
        return sysMenuMapper.selectMenuList(sysMenu);
    }

    public List<SysMenu> selectMenuListByRoleId(Long roleId) {
        return sysMenuMapper.selectMenuListByRoleId(roleId);
    }

    public List<MenuTree> getMenuTree() {
        Long roleId = 0L;
        List<SysMenu> menus = this.selectMenuListByRoleId(roleId);
        List<MenuTree> menuTree = new ArrayList<>(menus.size());
        buildTree(menus, menuTree);
        return menuTree;
    }

    private void buildTree(List<SysMenu> menus, List<MenuTree> menuTree) {
        Iterator<SysMenu> iterator = menus.iterator();
        while (iterator.hasNext()) {
            SysMenu menu = iterator.next();
            if (!this.hasParent(menu)) {
                MenuTree tree = this.createMenuTree(menu);
                this.fetchChild(menus, tree);
                menuTree.add(tree);
            }
        }
    }

    private void fetchChild(List<SysMenu> menus, MenuTree tree) {
        List<SysMenu> childList = menus.stream()
                .filter(item -> item.getParentId() != null && item.getParentId().equals(tree.getId()))
                .collect(Collectors.toList());
        List<MenuTree> childTreeList = new ArrayList<>();
        for (SysMenu sysMenu : childList) {
            MenuTree childTree = this.createMenuTree(sysMenu);
            childTreeList.add(childTree);
            fetchChild(menus, childTree);
        }
        tree.setChildrens(childTreeList);
    }

    private boolean hasParent(SysMenu menu) {
        return menu.getParentId() != null && menu.getParentId() != 0L;
    }

    private MenuTree createMenuTree(SysMenu menu) {
        return new MenuTree(menu.getId(), menu.getMenuName(), menu.getRouterPath(), menu.getParentId());
    }
}
